package com.jlboot.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jlboot.core.base.BaseSearchDto;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author wangsanfei
 * @version 1.0
 * Create by 2024/1/8 14:26
 */
public class RequestUtil {

    private static final String postData="postData";

    public static JSONObject parseJsonBody(HttpServletRequest request){
        String rawData = com.jfinal.kit.HttpKit.readData(request);
        if(StrKit.isBlank(rawData)){
            rawData=request.getParameter("postData");
        }
        return JSON.parseObject(rawData);
    }

    public static <T> T parseJsonBody(HttpServletRequest request,Class<T> tClass){
        String rawData = com.jfinal.kit.HttpKit.readData(request);
        if(StrKit.isBlank(rawData)){
            rawData=request.getParameter("postData");
        }
        return JSON.parseObject(rawData,tClass);
    }

    public static BaseSearchDto parseToBaseSearchDto(HttpServletRequest request){
        BaseSearchDto searchDto=new BaseSearchDto();

        Map<String,String[]> paramMap=request.getParameterMap();
        Map<String,Object> search=new HashMap<>();

        int page=1;
        int limit=10;

        String pageStr=request.getParameter("page");
        if(StrKit.notBlank(pageStr)){
            page=Integer.parseInt(pageStr);
        }

        String limitStr=request.getParameter("limit");
        if(StrKit.notBlank(limitStr)){
            limit=Integer.parseInt(limitStr);
        }

        if(limit>1000){
            //防止有人调用数据，每页最多1000条数据
            limit=1000;
        }

        Set<String> keys=paramMap.keySet();
        for (String key : keys) {
            if(!"page".equals(key)&&!"limit".equals(key)){
                String[] value=paramMap.get(key);
                if(value!=null&&value.length>0){
                    search.put(key,value[0]);
                }
            }
        }

        searchDto.setPage(page);
        searchDto.setLimit(limit);
        searchDto.setSearch(search);
        return searchDto;
    }

    public static BaseSearchDto parseJsonBodyToBaseSearchDto(HttpServletRequest request){
        String rawData = com.jfinal.kit.HttpKit.readData(request);
        if(StrKit.isBlank(rawData)){
            rawData=request.getParameter("postData");
        }
        return JSON.parseObject(rawData,BaseSearchDto.class);
    }

    public static void main(String[] args) {
        String json="{'a':'1'}";
        JSONObject jsonObject=JSON.parseObject(json);

        System.out.println(jsonObject.get("a"));;
    }

}
